<?php

namespace App\V3\V3_2_7\Services;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\OutAnimalTagModel;
use Hanson\Foundation\Log;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class OutAnimalTagService
{
    public static function add($data, $time): ?JsonResponse
    {
        DB::beginTransaction();
        try {
            if(empty($data['tag_content']))
                throw new \Exception('请填写标签内容!');
            CommonService::operateResult($data['user_id'], $time, $data, '创建成功');
            OutAnimalTagModel::query()->insert($data);
            DB::commit();
            return success();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('创建宠物出库标签异常' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }

    public static function update($data, $time)
    {
        DB::beginTransaction();
        try {
            if(empty($data['tag_content']))
                throw new \Exception('请填写标签内容!');
            $info = OutAnimalTagModel::query()
                ->where([
                    'id' => $data['id'],
                    'delete_flag' => 0
                ])->first();
            if (empty($info))
                throw new \Exception('没有找到标签信息');
            CommonService::operateResult($data['user_id'], $time, $data, '修改成功');
            unset($data['tag_id']);
            OutAnimalTagModel::query()
                ->where('id', $info['id'])->update($data);
            DB::commit();
            return success();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('修改宠物出库标签异常' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }

    public static function del($data, $time): ?JsonResponse
    {
        DB::beginTransaction();
        try {
            $info = OutAnimalTagModel::query()
                ->where([
                    'id' => $data['id'],
                    'delete_flag' => 0
                ])->first();
            if (empty($info))
                throw new \Exception('没有找到标签信息');
            CommonService::operateResult($data['user_id'], $time, $data, '删除成功');
            unset($data['tag_id']);
            OutAnimalTagModel::query()
                ->where('id', $info['id'])->update(['delete_flag' => 1]);
            DB::commit();
            return success();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('删除宠物出库标签异常' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }

    public static function list($data)
    {
        return OutAnimalTagModel::query()
            ->select(
                'id',
                'tag_content'
            )->where([
                'delete_flag' => 0,
                'main_id' => $data['main_id'],
            ])->orderBy('created_at','desc')->get();
    }
}
